package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/models"

	"github.com/beego/beego/v2/server/web"
)

// VenueController 场地管理控制器
type VenueController struct {
	web.Controller
}

// StoreName 存储门店名称的临时字段
type Venue struct {
	models.Venue
	StoreName string `json:"store_name" orm:"-"` // 门店名称，不存储到数据库
}

// VenueListRequest 场地列表请求参数
type VenueListRequest struct {
	Page        int    `json:"page" form:"page"`
	PageSize    int    `json:"pageSize" form:"pageSize"`
	Name        string `json:"name" form:"name"`
	Status      int8   `json:"status" form:"status"`
	StoreId     int64  `json:"store_id" form:"store_id"`
	VenueType   string `json:"venue_type" form:"venue_type"`
	MinCapacity int    `json:"min_capacity" form:"min_capacity"`
	MaxCapacity int    `json:"max_capacity" form:"max_capacity"`
}

// VenueCreateRequest 创建场地请求参数
type VenueCreateRequest struct {
	Name             string  `json:"name"`
	StoreId          int64   `json:"store_id"`
	Capacity         int     `json:"capacity"`
	Area             float64 `json:"area"`
	HourPrice        float64 `json:"hour_price"`
	TimeBasedPricing string  `json:"time_based_pricing"`
	DayPrice         float64 `json:"day_price"`
	Description      string  `json:"description"`
	SpecialNotice    string  `json:"special_notice"`
	Facilities       string  `json:"facilities"`
	Images           string  `json:"images"`
	Status           int8    `json:"status"`
	SortOrder        int     `json:"sort_order"`
	VenueType        string  `json:"venue_type"`
	OpeningHours     string  `json:"opening_hours"`
}

// VenueUpdateRequest 更新场地请求参数
type VenueUpdateRequest struct {
	Name             string  `json:"name"`
	StoreId          int64   `json:"store_id"`
	Capacity         int     `json:"capacity"`
	Area             float64 `json:"area"`
	HourPrice        float64 `json:"hour_price"`
	TimeBasedPricing string  `json:"time_based_pricing"`
	DayPrice         float64 `json:"day_price"`
	Description      string  `json:"description"`
	SpecialNotice    string  `json:"special_notice"`
	Facilities       string  `json:"facilities"`
	Images           string  `json:"images"`
	Status           int8    `json:"status"`
	SortOrder        int     `json:"sort_order"`
	VenueType        string  `json:"venue_type"`
	OpeningHours     string  `json:"opening_hours"`
}

// BatchRequest 批量获取请求
type BatchRequest struct {
	Ids []int64 `json:"ids"`
}

// GetOne 获取场地详情
func (c *VenueController) GetOne() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取场地ID
	id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
	if id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的场地ID",
		}
		c.ServeJSON()
		return
	}

	// 获取场地信息
	venue, err := models.GetVenueById(id)
	if err != nil || venue == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "场地不存在",
		}
		c.ServeJSON()
		return
	}

	// 获取场地对应的门店信息
	store, err := models.GetStoreById(venue.StoreId)
	if err != nil || store == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "场地所属门店不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	resourcePermResult := CheckFranchiseResourcePermission(permResult.Admin, store.FranchiseId)
	if !resourcePermResult.Success {
		RespondWithError(&c.Controller, resourcePermResult)
		return
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取场地详情成功",
		"data":    venue,
	}
	c.ServeJSON()
}

// List 获取场地列表
func (c *VenueController) List() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取请求参数
	page, _ := strconv.Atoi(c.GetString("page"))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(c.GetString("pageSize"))
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 10
	}

	name := c.GetString("name")
	status, _ := c.GetInt8("status", -1)
	storeId, _ := c.GetInt64("store_id", 0)
	venueType := c.GetString("venue_type")
	minCapacity, _ := c.GetInt("min_capacity", 0)
	maxCapacity, _ := c.GetInt("max_capacity", 0)

	// 构建过滤条件
	filters := make(map[string]interface{})
	if name != "" {
		filters["name"] = name
	}
	if status >= 0 {
		filters["status"] = int8(status)
	}
	if storeId > 0 {
		filters["store_id"] = storeId
	}
	if venueType != "" {
		filters["venue_type"] = venueType
	}
	if minCapacity > 0 {
		filters["min_capacity"] = minCapacity
	}
	if maxCapacity > 0 {
		filters["max_capacity"] = maxCapacity
	}

	// 加盟商只能查看自己的数据
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	// 查询场地列表
	venues, total, err := models.GetVenueList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取场地列表失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取场地列表成功",
		"data": map[string]interface{}{
			"list":  venues,
			"total": total,
		},
	}
	c.ServeJSON()
}

// Create 创建场地
func (c *VenueController) Create() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var req VenueCreateRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 验证门店存在性并检查加盟商权限
	if req.StoreId > 0 {
		store, err := models.GetStoreById(req.StoreId)
		if err != nil || store == nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "所选门店不存在",
			}
			c.ServeJSON()
			return
		}

		// 验证加盟商权限
		resourcePermResult := CheckFranchiseResourcePermission(permResult.Admin, store.FranchiseId)
		if !resourcePermResult.Success {
			RespondWithError(&c.Controller, resourcePermResult)
			return
		}
	}

	// 创建场地
	venue := &models.Venue{
		Name:             req.Name,
		StoreId:          req.StoreId,
		Capacity:         req.Capacity,
		Area:             req.Area,
		HourPrice:        req.HourPrice,
		TimeBasedPricing: req.TimeBasedPricing,
		DayPrice:         req.DayPrice,
		Description:      req.Description,
		Facilities:       req.Facilities,
		SpecialNotice:    req.SpecialNotice,
		Images:           req.Images,
		Status:           req.Status,
		SortOrder:        req.SortOrder,
		VenueType:        req.VenueType,
		OpeningHours:     req.OpeningHours,
	}
	venue.FranchiseId = permResult.Admin.FranchiseId
	// 设置创建者信息
	venue.CreatedBy = permResult.Admin.Username
	venue.UpdatedBy = permResult.Admin.Username
	venue.BeforeInsert()
	// 保存到数据库
	id, err := models.CreateVenue(venue)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建场地失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建场地成功",
		"data": map[string]interface{}{
			"id": id,
		},
	}
	c.ServeJSON()
}

// Update 更新场地
func (c *VenueController) Update() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取场地ID
	id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
	if id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的场地ID",
		}
		c.ServeJSON()
		return
	}

	// 获取场地信息
	venue, err := models.GetVenueById(id)
	if err != nil || venue == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "场地不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证场地所属门店的加盟商权限
	store, err := models.GetStoreById(venue.StoreId)
	if err != nil || store == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "场地所属门店不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	resourcePermResult := CheckFranchiseResourcePermission(permResult.Admin, store.FranchiseId)
	if !resourcePermResult.Success {
		RespondWithError(&c.Controller, resourcePermResult)
		return
	}

	// 解析请求参数
	var req VenueUpdateRequest
	err = json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 如果更改了所属门店，验证新门店的加盟商权限
	if req.StoreId > 0 && req.StoreId != venue.StoreId {
		newStore, err := models.GetStoreById(req.StoreId)
		if err != nil || newStore == nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "所选门店不存在",
			}
			c.ServeJSON()
			return
		}

		// 验证加盟商权限
		newResourcePermResult := CheckFranchiseResourcePermission(permResult.Admin, newStore.FranchiseId)
		if !newResourcePermResult.Success {
			RespondWithError(&c.Controller, newResourcePermResult)
			return
		}
	}

	// 更新场地信息
	venue.Name = req.Name
	venue.StoreId = req.StoreId
	venue.Capacity = req.Capacity
	venue.Area = req.Area
	venue.HourPrice = req.HourPrice
	venue.TimeBasedPricing = req.TimeBasedPricing
	venue.DayPrice = req.DayPrice
	venue.Description = req.Description
	venue.Facilities = req.Facilities
	venue.SpecialNotice = req.SpecialNotice
	venue.Images = req.Images
	venue.Status = req.Status
	venue.SortOrder = req.SortOrder
	venue.VenueType = req.VenueType
	venue.OpeningHours = req.OpeningHours

	// 设置更新者信息
	venue.UpdatedBy = permResult.Admin.Username
	venue.BeforeUpdate()

	// 保存到数据库
	err = models.UpdateVenue(venue)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新场地失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新场地成功",
	}
	c.ServeJSON()
}

// Delete 删除场地
func (c *VenueController) Delete() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取场地ID
	id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
	if id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的场地ID",
		}
		c.ServeJSON()
		return
	}

	// 获取场地信息
	venue, err := models.GetVenueById(id)
	if err != nil || venue == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "场地不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证场地所属门店的加盟商权限
	store, err := models.GetStoreById(venue.StoreId)
	if err != nil || store == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "场地所属门店不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	resourcePermResult := CheckFranchiseResourcePermission(permResult.Admin, store.FranchiseId)
	if !resourcePermResult.Success {
		RespondWithError(&c.Controller, resourcePermResult)
		return
	}

	// 删除场地
	err = models.DeleteVenue(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "删除场地失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "删除场地成功",
	}
	c.ServeJSON()
}

// Batch 批量获取场地信息
func (c *VenueController) Batch() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var req BatchRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 如果未提供ID列表，返回空数组
	if len(req.Ids) == 0 {
		c.Data["json"] = map[string]interface{}{
			"success": true,
			"message": "获取场地信息成功",
			"data":    []interface{}{},
		}
		c.ServeJSON()
		return
	}

	// 获取场地信息
	var venues []*Venue
	for _, id := range req.Ids {
		venue, err := models.GetVenueById(id)
		if err != nil || venue == nil {
			continue
		}

		// 检查加盟商权限
		if permResult.Admin.FranchiseId > 0 {
			// 获取场地对应的门店
			store, err := models.GetStoreById(venue.StoreId)
			if err != nil || store == nil {
				continue
			}

			// 验证权限
			if !models.CheckFranchisePermission(permResult.Admin.FranchiseId, store.FranchiseId) {
				continue
			}
		}

		// 添加门店名称信息
		store, _ := models.GetStoreById(venue.StoreId)
		storeName := ""
		if store != nil {
			storeName = store.Name
		}

		venueWithStore := &Venue{
			Venue:     *venue,
			StoreName: storeName,
		}
		venues = append(venues, venueWithStore)
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取场地信息成功",
		"data":    venues,
	}
	c.ServeJSON()
}
